package com.hmdp.utils;

import cn.hutool.core.lang.func.Func;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {
    public final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value,Long expireTime, TimeUnit timeUnit) {
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key, jsonStr,expireTime, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, Long expireTime, TimeUnit timeUnit ) {
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(expireTime)));
        //序列化写入redis
        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(key, jsonStr);
    }
    public <R,ID> R queryWithPassThrough(String keyPrefix,ID id,Class<R> type,
                                         Function<ID,R> dbFallback,Long expireTime, TimeUnit timeUnit) {
        String key=keyPrefix + id;
        //先查缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            RedisData redisData = JSONUtil.toBean(json,RedisData.class);
            R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
            return r;
        }
        if (json != null) {
            return null;
        }
        //再查数据库
        R r = dbFallback.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //写入redis
        this.set(key, JSONUtil.toJsonStr(r), expireTime, timeUnit);
        return r;
    }

    //商铺缓存重建的线程池
    private static final ExecutorService CACHE_REBUIDER_EXCUTOR = Executors.newFixedThreadPool(10);

    public <R,ID> R queryWithMLogicalExpire(String keyPrefix, ID id, Class<R> type, String lockName,Long lockExpireTime,
                                            Function<ID,R> dbFallback,Long time, TimeUnit timeUnit) {
        String key=keyPrefix + id;
        //先查缓存
        String cacheJSON = stringRedisTemplate.opsForValue().get(key);
        //未命中，直接返回空
        //因为此时已经进行数据预热，把数据库中的数据预先存进了redis中
        //所以说cacheShopJSON为null时，不需要再查数据库
        if (StrUtil.isBlank(cacheJSON)) {
            return null;
        }
        //拿出封装的数据和逻辑过期时间，反序列化成对象
        RedisData redisData = JSONUtil.toBean(cacheJSON, RedisData.class);
        //
        R cache = JSONUtil.toBean((JSONObject)redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期则直接返回数据
            return cache;
        }
        //过期，则尝试获取锁
        boolean isLock = tryLock(lockName,lockExpireTime);
        //获取成功，尝试重建缓存，开启新线程，更新过期时间
        if (isLock) {
            CACHE_REBUIDER_EXCUTOR.submit(()->{
                try {
                    R r = dbFallback.apply(id);
                    setWithLogicalExpire(key,r,time,timeUnit);
                    log.info("缓存重建了");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockName);
                }
            });
        }
        //返回过期数据
        return cache;
    }

    private boolean tryLock(String lockName,Long lockExpireTime) {
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(lockName, "1", lockExpireTime, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String lockName) {
        stringRedisTemplate.delete(lockName);
    }

    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
}
